#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include "epoll.h"


Epoll::Epoll(void):m_events(0),m_count(0),m_fd(-1)
{
	memset(&nullevent, 0, sizeof(nullevent));
}
Epoll::~Epoll(void)
{
	Close();
}
bool Epoll::Open(int count)
{
	if( -1 != m_fd )
	{
		return true;
	}
	m_events = (struct epoll_event*)malloc( count * sizeof(struct epoll_event) );
	if( m_events )
	{
		m_fd = epoll_create1(0);
		if( -1 == m_fd )
		{
			free(m_events);
			m_events = NULL;
			m_count = 0;
			return false;
		}
		m_count = count;
	}
	return true;
}
bool Epoll::Close(void)
{
	if( -1 == m_fd )
	{
		close(m_fd);
		m_fd = -1;
	}
	if( m_events )
	{
		free(m_events);
		m_events = NULL;
	}
	m_count = 0;
}
bool Epoll::AddEvent(int fd, int events)
{
	struct epoll_event event;

	event.data.fd = fd;
	event.events = events;
	int ret = epoll_ctl(m_fd, EPOLL_CTL_ADD, fd, &event);

	return (0 == ret);
}
bool Epoll::DelEvent(int fd, int events)
{
	struct epoll_event event;

	event.data.fd = fd;
	event.events = events;
	int ret = epoll_ctl(m_fd, EPOLL_CTL_DEL, fd, &event);

	return (0 == ret);
}
int Epoll::WaitEvent(int millisecond)
{
	if( -1 == m_fd || NULL == m_events )
	{
		return -1;
	}
	int ret  = epoll_wait(m_fd, m_events, m_count, millisecond);
	for(int i = 0; i < ret; i++)
	{
		printf("%s(%d, %08X)\n", __func__, m_events[i].data.fd, m_events[i].events);
	}
	return ret;
}
struct epoll_event& Epoll::operator[](int i)
{
	if( m_events )
	{
		return m_events[ (i % m_count) ];
	}
	return nullevent;
}
